package org.example.router;

import com.sun.net.httpserver.HttpExchange;
import org.example.HttpHandler;
import org.example.core.RequestContext;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 请求路由器 - 纯粹的路由逻辑，不包含业务
 */
public class RequestRouter {
    // 存储路径模式 -> HTTP处理器的映射
    private final Map<String, HttpHandler> routeMappings = new ConcurrentHashMap<>();

    public RequestRouter() {
    }

    /**
     * 注册HTTP处理器
     */
    public void registerHandler(HttpHandler handler) {
        for (String method : handler.supportedMethods()) {
            String key = createRouteKey(method, handler.getPathPattern());
            routeMappings.put(key, handler);
            System.out.println("Registered handler: " + key + " -> " + handler.getClass().getSimpleName());
        }
    }

    /**
     * 查找并处理路由
     */
    public RouteMatch findAndHandleRoute(String method, String path, HttpExchange exchange) {
        // 查找匹配的处理器
        HandlerMatch handlerMatch = findHandler(method, path);

        if (handlerMatch != null) {
            try {
                // 准备请求上下文
                RequestContext context = createRequestContext(exchange, handlerMatch.pathParams);

                // 调用业务处理器
                String result = handlerMatch.handler.handle(
                        exchange,
                        handlerMatch.pathParams,
                        context.getQueryParams(),
                        context.getRequestBody()
                );

                return new RouteMatch(result);
            } catch (Exception e) {
                return new RouteMatch("ERROR:500:Internal Server Error: " + e.getMessage());
            }
        }

        return null;
    }

    /**
     * 查找匹配的处理器
     */
    private HandlerMatch findHandler(String method, String path) {
        // 先尝试精确匹配（方法+路径）
        String exactKey = createRouteKey(method, path);
        HttpHandler exactHandler = routeMappings.get(exactKey);
        if (exactHandler != null) {
            return new HandlerMatch(exactHandler, Collections.emptyMap());
        }

        // 查找路径模式匹配
        for (Map.Entry<String, HttpHandler> entry : routeMappings.entrySet()) {
            String key = entry.getKey();
            String[] parts = key.split(":", 2);
            String routeMethod = parts[0];
            String routePattern = parts[1];

            if (routeMethod.equals(method) || routeMethod.equals("ANY")) {
                Map<String, String> pathParams = extractPathParameters(routePattern, path);
                if (pathParams != null) {
                    return new HandlerMatch(entry.getValue(), pathParams);
                }
            }
        }

        return null;
    }

    /**
     * 创建路由键
     */
    private String createRouteKey(String method, String pattern) {
        return method.toUpperCase() + ":" + pattern;
    }

    /**
     * 路径模式匹配和参数提取
     */
    private Map<String, String> extractPathParameters(String pattern, String path) {
        Map<String, String> params = new HashMap<>();
        String[] patternParts = pattern.split("/");
        String[] pathParts = path.split("/");

        if (patternParts.length != pathParts.length) {
            return null;
        }

        for (int i = 0; i < patternParts.length; i++) {
            if (patternParts[i].startsWith("{") && patternParts[i].endsWith("}")) {
                // 参数部分，匹配任何非空字符串
                if (pathParts[i].isEmpty()) {
                    return null;
                }
                String paramName = patternParts[i].substring(1, patternParts[i].length() - 1);
                params.put(paramName, pathParts[i]);
            } else if (!patternParts[i].equals(pathParts[i])) {
                // 固定部分必须精确匹配
                return null;
            }
        }
        return params;
    }

    /**
     * 创建请求上下文
     */
    private RequestContext createRequestContext(HttpExchange exchange, Map<String, String> pathParams) {
        // 解析查询参数
        Map<String, String> queryParams = new HashMap<>();
        String query = exchange.getRequestURI().getQuery();
        if (query != null) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    queryParams.put(keyValue[0], keyValue[1]);
                } else if (keyValue.length == 1) {
                    queryParams.put(keyValue[0], "");
                }
            }
        }

        // 读取请求体
        String requestBody = "";
        try {
            InputStream requestBodyStream = exchange.getRequestBody();
            Scanner scanner = new Scanner(requestBodyStream).useDelimiter("\\A");
            requestBody = scanner.hasNext() ? scanner.next() : "";
        } catch (Exception e) {
            // 忽略请求体读取错误
        }

        return new RequestContext(exchange, pathParams, queryParams, requestBody);
    }

    /**
     * 获取所有注册的路由
     */
    public Map<String, String> getRegisteredRoutes() {
        Map<String, String> routes = new HashMap<>();
        routeMappings.forEach((key, handler) -> {
            routes.put(key, handler.getClass().getSimpleName());
        });
        return routes;
    }

    /**
     * 处理器匹配结果
     */
    private static class HandlerMatch {
        final HttpHandler handler;
        final Map<String, String> pathParams;

        HandlerMatch(HttpHandler handler, Map<String, String> pathParams) {
            this.handler = handler;
            this.pathParams = pathParams;
        }
    }

    /**
     * 路由匹配结果
     */
    public static class RouteMatch {
        public final String result;

        public RouteMatch(String result) {
            this.result = result;
        }
    }
}